/* ----------------------------------------------------------------------------

	pax.widget.modal.js Copyright (C) 2008, 2009 Mikkel Bergmann, Pointful

	Licence
	-------
	
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

	See lgpl.txt for licence details

---------------------------------------------------------------------------- */
/*
	Script: pax.widget.modal
		Modal widget script
		
	Author:
		Mikkel Bergmann, <http://www.pointful.com>

*/


var pax = pax || {};
pax.widget = pax.widget || {};
pax.widget.modal = pax.widget.modal || {};

//      IE6 hack value container, so we can reset values after hack is finished.
pax.widget.modal.ie6SelectHackValues = {};


/*
	WIP
	---

	[done]	. Create a default surround template, and allow overriding in the init.
	. Add a loader class
	. Create simple slideshow functionality, then a plugin for the detailed implementation
		- ability to dynamically change an image
		- The detailed implementation will simply use a custom template and script.
	. Allow using existing markup, eg like here:

		http://colorpowered.com/colorbox/

*/
pax.widget.modal.model = function( args ) {
	var model = {
		message: '<a href="javascript:pax.widget.modal.hide();">Close</a>No message specified.',
		footerMessage: null,	//	Optional message for the footer
		url: null,				//	Ajax parameter
		src: null,				//	iframe parameter
		srcElement: null,       //  Optional in-page element that contains the contents for our modal
		contentDisplay: null,	//	contentDisplay parameter
		width: 400,				//	Width in pixels
		height: 300,			//	Height in pixels
		fitViewport: true,		//	Do we shrink the modal to fit, if the viewport is too small
		footerHeight: 20,		//	Height of footer in pixels
		showFooter: true,		//	Show the footer
		iframe: {				//	iframe properties
			scrolling: 'auto',
			frameborder: '0',
			hspace: '0',
			src: 'javascript:false;',
			id: 'paxModalBoxIframe',
			name: null,
			width: 400,
			height: 300
		},
		template: pax.widget.modal.template()
	};
	
	if( args ) {
		var oldIframe = model.iframe;
		model = pax.defaultArgs( model, args );
		model.iframe = pax.defAddArgs( oldIframe, args.iframe );
		//	Always override the width / height with args
		model.iframe.width = (args.width)? args.width: model.iframe.width; 
		model.iframe.height = (args.height)? args.height: model.iframe.height; 
	}
	
	return model;
};

//      initialise the modal box
/*	Method: pax.widget.modal.init
	Initialises a modal box widget
	
	Parameters:
		args
		* message - The contents of the modal box
		* footerMessage - Optional message for the footer
		* url - Ajax parameter, specifies what URL to make an ajax call to, uses GET
		* src - iframe parameter, specifes what source for an iframe; do not use with url parameter
		* srcElement - Optional in-page element that contains the contents for our modal
		* contentDisplay - What CSS display style to use for the content, useful for integrating with different designs
		* width - Width of content in pixels, default is 400
		* height - Height of content in pixels, default is 300
		* fitViewport - Do we shrink the modal to fit, if the viewport is too small, default is true
		* footerHeight - Height of footer in pixels, default is 20
		* showFooter - Show the footer, default is true
		* iframe - iframe properties, should not be chnaged, see source if you need to change things
		* template - pax template to use for rendering the modal, default is from pax.widget.modal.template()

	Returns:
		nothing

	Example:
		(start code)
			Modal example
            <p>
                <input id="showModalButton" type="button" value="Show modal"/>
            </p>
			
            Click the button do see the modal
            [:.
                pax.event.bind( pax.$( 'showModalButton' ), 'click', function() {
                    pax.widget.modal.init( {
                        message: 'This is the modal box message'
                    } );
                } );
			:]
		(end)
*/
pax.widget.modal.init = function( args ) {
	var model = pax.widget.modal.model( args );
	var element = pax.$( 'paxModalBox' );
	if( ! element ) {
		element = pax.util.genElement( 'DIV', { id: 'paxModalBox' } );
		document.body.appendChild( element );
	}

	var offsetLeft = 0;
	var offsetTop = 0;
	
	//	//	For ie6, we add the scroll offsets
	//	if( pax.isIe6Down ) {
		//var offsetLeft = parseInt( document.documentElement.scrollLeft, 10 );
		//var offsetTop = parseInt( document.documentElement.scrollTop, 10 );
	//	}
	
	//	Adjust height and width if necessary
	if( model.fitViewport ) {
		var wDims = pax.util.getWindowDimensions();
		model['width'] = ( model['width'] < wDims['width'] )? model['width']: wDims['width'];
		model['height'] = ( model['height'] < wDims['height'] )? model['height']: wDims['height'];
	}
	
	pax.util.setStyle( element, {
		//	WIP: moving height and width to content DIV
		//	Note: this works, except in IE6 where the box is too wide??? <-- Need to install the debug bar thingy in my IE6 to fix this.
		xwidth: model['width'] + 'px',
		xheight: model['height'] + 'px',
		marginLeft: offsetLeft + parseInt( '-' + parseInt( ( model['width'] / 2 ), 10 ) ) + 'px',
		marginTop: offsetTop + parseInt( '-' + parseInt( ( model['height'] / 2 ), 10 ) ) + 'px'
	} );
	
	//	Add the contents
	if( model['src'] ) {			//	If iframe
		var attribs = model.iframe;
		attribs.name = (attribs.name)? attribs.name: attribs.id + '_' + Math.round( Math.random() * 1000 );
		attribs.src = model.src;
		
		var myIframe =	"<iframe width='" + attribs.width + "px' scrolling='" + attribs.scrolling + "' height='" + 
						(attribs.height - ( (model.showFooter)? model.footerHeight: 0 ) ) + 
						"px' frameborder='" + attribs.frameborder + "' hspace='" + attribs.hspace + "' src='" + attribs.src + 
						"' id='" + attribs.id + "' name='" + attribs.name + "'/></iframe>";
		
		model.content = myIframe;
	} else if( model['url'] ) {		//	If ajax
		pax.get( model.url, function( xml, txt, url ) {
			model.content = txt;
			pax.widget.modal._init( element, model );
		} );
	} else {						//	If HTML or text
		model.content = model['message'];
	}
	
	model.footerContent = model['footerMessage'];

	//	Init the modal box, unless it's ajax, in which case the callback function handles it.	
	if( ! model['url'] )pax.widget.modal._init( element, model );
};


//	Initialise the modal box
pax.widget.modal._init = function( element, model ) {
	//	Show overlay
	pax.widget.modal.overlay( model );
	
	//	Initialise widget and render
	var modal = pax.widget.init( {
		model: model,
		template: ( ( model.srcElement )? model.srcElement.innerHTML: model.template ),
		target: element
	} );
	
	modal.render();

	element.style.display = '';
};


//	Default modal template
pax.widget.modal.template = function() {

	//	xwidth: model['width'] + 'px',
	//	xheight: model['height'] + 'px',
	
	//	In IE6, the templatePaxModalBox is the wrong width...
	
	return "" +
		"<div id='templatePaxModalBox'>" +
		"	<div id='templatePaxModalBoxContent' style='width: [:= width :]px; height: [:= height :]px;" + 
        " [:= ( contentDisplay != null )? 'display:'+contentDisplay:'' :]'>[:= content :]</div>" +
		"	[: if( showFooter ) { :]" +
		"	<div id='templatePaxModalBoxFooter'>" +
		"		<a href='javascript:pax.widget.modal.hide();' class='paxModalCloseButton' alt='X'></a>" +
		"		<div id='templatePaxModalBoxFooterContent'>" +
		"			[: if( footerContent ) { :][:= footerContent :][: } :]" +
		"		</div>" +
		"	</div>" +
		"	[: } :]" +
		"</div>" +
	"";
};


/*	Method: pax.widget.modal.hide
	Hides the modal box
	
	Parameters:
        none - Per definition, we can only have one modal box per window at a time

	Returns:
		nothing

*/
pax.widget.modal.hide = function() {
	var mod = pax.$( 'paxModalBox' );
	if( mod )mod.style.display = 'none';
	pax.widget.modal.hideOverlay();
};


//	Insert the overlay (if it doesn't exist)
pax.widget.modal.overlay = function( model ) {

	var element = pax.$( 'paxModalOverlayBox' );
	if( !element ) {
		element = (element) ? element : pax.util.genElement('DIV', { 'id': 'paxModalOverlayBox', 'class': 'paxModalOverlay' } );
		document.body.appendChild(element);
	}
	element.style.display = '';

	//	IE6 hack - the body 
	if( pax.isIe6Down ) {
		//	Save body settings for later
		pax.widget.modal.ie6SelectHackValues['body'] = {
			height: document.body.style.height,
			width: document.body.style.width,
			overflow: document.body.style.overflow
		};
		pax.widget.modal.ie6SelectHackValues['document'] = {
			overflowY: document.documentElement.style.overflowY,
			height: document.documentElement.style.height
		};

		document.body.style.height = "100%";
		document.body.style.width = "100%";
		document.body.style.overflow = "hidden";
		document.documentElement.style.overflowY = "hidden";
		document.documentElement.style.height = "100%";
		
		element.style.zIndex = 100;

		// Only insert iframe, if it doesn't already exist
		if( ! pax.widget.modal.ie6SelectHackValues['iframe'] ) {
			myZIndex = element.style.zIndex - 1;      // Insert iframe layer just below Div
			// The ugly string below is an iframe with the correct parameters.
			var myFrameText = "<iframe src=\"javascript:false;\" id=\"paxModalOverlayIframe\"" + 
                " class=\"paxModalOverlay\" scrolling=\"no\" frameborder=\"0\" style=\"z-index:"+
                myZIndex+";filter:'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';\"" + 
                "></iframe>";
			element.insertAdjacentHTML('afterEnd', myFrameText);
			pax.widget.modal.ie6SelectHackValues['iframe'] = pax.$( 'paxModalOverlayIframe' );
		}
	}
};


//	Hides the overlay
pax.widget.modal.hideOverlay = function() {
	var mo = pax.$( 'paxModalOverlayBox' );
	if( mo )mo.style.display = 'none';

	//	IE6 hack to hide selects.
	if( pax.isIe6Down ) {
		//	Remove iframe
		if( pax.widget.modal.ie6SelectHackValues['iframe'] ) {
			pax.widget.modal.ie6SelectHackValues['iframe'].removeNode( true );
			pax.widget.modal.ie6SelectHackValues['iframe'] = null;
		}
		document.body.style.height = pax.widget.modal.ie6SelectHackValues['body'].height;
		document.body.style.width = pax.widget.modal.ie6SelectHackValues['body'].width;
		document.body.style.overflow = pax.widget.modal.ie6SelectHackValues['body'].overflow;
		document.documentElement.style.overflowY = pax.widget.modal.ie6SelectHackValues['document'].overflowY;
		document.documentElement.style.height = pax.widget.modal.ie6SelectHackValues['document'].height;
	}
};
